package com.yuanlrc.hotel.home;

import com.yuanlrc.common.core.controller.BaseController;
import com.yuanlrc.common.core.domain.AjaxResult;
import com.yuanlrc.common.utils.MessageUtils;
import com.yuanlrc.common.utils.security.Md5Utils;
import com.yuanlrc.hotel.about.domain.About;
import com.yuanlrc.hotel.about.service.IAboutService;
import com.yuanlrc.hotel.account.domain.Account;
import com.yuanlrc.hotel.account.service.IAccountService;
import com.yuanlrc.hotel.news.domain.News;
import com.yuanlrc.hotel.news.service.INewsService;
import com.yuanlrc.hotel.rommType.domain.RoomType;
import com.yuanlrc.hotel.rommType.service.IRoomTypeService;
import com.yuanlrc.hotel.room.domain.Room;
import com.yuanlrc.hotel.room.service.IRoomService;
import com.yuanlrc.system.utils.SessionUtil;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.MD5;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 登录和注册
 * @author wangzihan
 * @date : 2020/11/18 15:20
 */
@Controller
@RequestMapping("/home/index")
public class HomeLoginController extends BaseController {

    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAboutService iAboutService;
    @Autowired
    private INewsService iNewsService;

    @Autowired
    private IRoomTypeService roomTypeService;

    @Autowired
    private IRoomService roomService;

    /**
     * 前台登录跳转
     *
     * @return
     */
    @GetMapping("/login")
    public String homeLogin() {
        return "home/login";
    }

    /**
     * 前台首页跳转
     *
     * @return
     */
    @GetMapping("/index")
    public String homeIndex(Model model) {
        Account logindeAccount = SessionUtil.getLogindeAccount();
        About about = iAboutService.selectOneAbout();
        List<News> news = iNewsService.selectFourNewsList(new News());
        News news1 = iNewsService.selectOneNews();

        List<RoomType> roomTypes = roomTypeService.selectRoomTypeIndexList();
        List<Room> rooms = roomService.selectRoomListTop8();

        model.addAttribute("news",news1);
        model.addAttribute("about",about);
        model.addAttribute("newsList",news);
        model.addAttribute("logindeAccount",logindeAccount);
        model.addAttribute("roomTypes",roomTypes);
        model.addAttribute("rooms",rooms);
        return "home/index";
    }


    /**
     * 前台用户登录
     *
     * @param loginphone 登录手机号
     * @param password   登录密码
     * @param code       验证码
     * @return 成功或错误信息
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestParam(value = "loginphone", required = false) String loginphone,
                            @RequestParam(value = "loginpassword", required = false) String password,
                            @RequestParam(value = "code", required = false) String code) {

        //通过登录的手机号去查询用户
        Account findAccount = accountService.selectAccountByPhone(loginphone);
        AjaxResult error = AjaxResult.error();

        //判断是否有该用户
        if (findAccount == null) {
            error.put("code", 501);
            return error;
        }
        //密码验证
        String hash = Md5Utils.hash(password);
        if (!hash.equals(findAccount.getPassword())) {
            error.put("code", 502);
            return error;
        }

        //效验验证码
        Object attribute = SessionUtil.get("home_login_img_code");
        if (attribute == null) {
            return error;
        }
        if (!code.equalsIgnoreCase(attribute.toString())) {
            error.put("code", 503);
            return error;
        }

        //判断该用户是否可用
        if (findAccount.getState() == 0){
            error.put("code",504);
            return error;
        }
        //表示都通过了
        //把用户放到session中
        SessionUtil.set("account",findAccount);

        //验证码清空
        SessionUtil.set("home_login_img_code", null);


        return success();
    }


    /**
     * 前台用户注册
     * @param account 用户注册信息
     * @param code    验证码
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public AjaxResult register(Account account, @RequestParam(value = "rcode",required = false) String code) {

        AjaxResult error = AjaxResult.error();
        //手机号验证
        String chkphone = "^1[3|4|5|7|8]\\d{9}$";
        Pattern r = Pattern.compile(chkphone);
        if (account.getPhone() == null) {
            error.put("code", 501);
            return error;
        }
        Matcher m = r.matcher(account.getPhone());
        if (!m.matches()) {
            error.put("code", 502);
            return error;
        }

        //邮箱验证
        String pattern = "^(?:[a-zA-Z0-9]+[_\\-\\+\\.]?)*[a-zA-Z0-9]+@(?:([a-zA-Z0-9]+[_\\-]?)*[a-zA-Z0-9]+\\.)+([a-zA-Z]{2,})+$";
        Pattern emailReg = Pattern.compile(pattern);
        Matcher email = emailReg.matcher(account.getEmail());
        if (!email.matches()) {
            error.put("code", 504);
            return error;
        }

        //验证码验证
        Object attribute = SessionUtil.get("home_register_img_code");
        if (attribute == null) {
            error.put("code", 505);
            return error;
        }
        if (!code.equalsIgnoreCase(attribute.toString())) {
            error.put("code", 506);
            return error;
        }
        //表示都通过了
        //如果该手机号已经注册让他去登录
        Account findAccount = accountService.selectAccountByPhone(account.getPhone());
        if (findAccount != null) {
            error.put("code", 507);
            return error;
        }

        //效验通过，进行新增
        account.setState(1);
        //md5加密
        String hash = Md5Utils.hash(account.getPassword());
        account.setSex(2l);
        account.setPassword(hash);
        int i = accountService.insertAccount(account);
        if (i == 0) {
            error.put("code", 508);
            return error;
        }
        //验证码清空
        SessionUtil.set("home_register_img_code", null);

        return success();

    }


    @GetMapping("/logout")
    public String logoutAccount(){
        HttpSession session = getSession();
        session.removeAttribute("account");
        return "redirect:index";
    }


    @PostMapping("/forgetPassword")
    @ResponseBody
    public AjaxResult forgetPassword(Account account, @RequestParam(value = "code", required = false) String code){

        //通过登录的手机号去查询用户
        Account findAccount = accountService.selectAccountByPhone(account.getPhone());
        AjaxResult error = AjaxResult.error();
        //判断手机号和姓名是否匹配
        if (!findAccount.getName().equals(account.getName())){
            error.put("code",700);
            return error;
        }
        //判断重设密码是否与原密码相同
        String hash1 = Md5Utils.hash(account.getPassword());
        if (hash1.equals(findAccount.getPassword())){
            error.put("code",702);
            return error;
        }
        //效验验证码
        Object attribute = SessionUtil.get("home_login_img_code");
        if (attribute == null) {
            return error;
        }
        if (!code.equalsIgnoreCase(attribute.toString())) {
            error.put("code", 701);
            return error;
        }

        //都通过说明正确，重新设置密码
        String hash = Md5Utils.hash(account.getPassword());
        findAccount.setPassword(hash);
        accountService.updateAccount(findAccount);

        //验证码清空
        SessionUtil.set("home_login_img_code", null);

        return success();
    }

}


